package rexsee.communication;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.utilities.Escape;
import rexsee.core.utilities.Utilities;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;

public class RexseeMMS implements JavascriptInterface {

	public static final String INTERFACE_NAME = "MMS";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeMMS(childBrowser);
	}

	public static String CONTENT_URI_MMS = "content://mms/";
	public static String CONTENT_URI_MMS_INBOX = "content://mms/inbox";
	public static String CONTENT_URI_MMS_SENT = "content://mms/sent";
	public static String CONTENT_URI_MMS_PART = "content://mms/part";

	private final Context mContext;
	private final Browser mBrowser;

	public static String[] MMS_COLUMNS = new String[]{
			"_id", //0 
			"thread_id", //1 
			"date", //2
			"msg_box", //3;  1:inBox 2:sent 3:draft 4:outBox
			"read", //4; 0:not read 1:read; default is 0
			"sub" //5
	};
	public static String[] PART_COLUMNS = new String[]{
			"_id", //0 
			"mid", //1 
			"seq", //2 
			"ct", //3
			"name", //4 
			"chset", //5 
			"cd", //6 
			"fn", //7 
			"cid", //8 
			"cl", //9
			"ctt_s", //10 
			"ctt_t", //11 
			"_data", //12 
			"text" //13 
	};
	public static String[] ADDR_COLUMNS = new String[]{
			"_id", //0 
			"msg_id", //1 
			"contact_id", //2
			"address", //3
			"type", //4; 
			"charset" //5; 
	};

	public RexseeMMS(Browser browser) {
		mBrowser = browser;
		mContext = browser.getContext();
	}

	//JavaScript Interface
	public String getContentUris() {
		String rtn = "{";
		rtn += "\"mms\":\"" + CONTENT_URI_MMS + "\"";
		rtn += ",\"inbox\":\"" + CONTENT_URI_MMS_INBOX + "\"";
		rtn += ",\"sent\":\"" + CONTENT_URI_MMS_SENT + "\"";
		rtn += ",\"part\":\"" + CONTENT_URI_MMS_PART + "\"";
		rtn += "}";
		return rtn;
	}

	public String get(int number) {
		return getData(null, number);
	}
	public String getUnread(int number) {
		return getData("msg_box=1 AND read=0", number);
	}
	public String getRead(int number) {
		return getData("msg_box=1 AND read=1", number);
	}
	public String getInbox(int number) {
		return getData("msg_box=1", number);
	}
	public String getSent(int number) {
		return getData("msg_box=2", number);
	}
	public String getByThread(int thread) {
		return getData("thread_id=" + thread, 0);
	}
	public String getData(String selection, int number) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		try {
			if (number > 0) {
				cursor = contentResolver.query(Uri.parse(CONTENT_URI_MMS), MMS_COLUMNS, selection, null, "date desc limit " + number);
			} else {
				cursor = contentResolver.query(Uri.parse(CONTENT_URI_MMS), MMS_COLUMNS, selection, null, "date desc");
			}
			if (cursor == null || cursor.getCount() == 0) return "[]";
			String rtn = "";
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				if (i > 0) rtn += ",";
				rtn += "{";
				rtn += "\"_id\":" + cursor.getString(0);
				rtn += ",\"thread_id\":" + cursor.getString(1);
				rtn += ",\"date\":" + cursor.getString(2);
				rtn += ",\"msg_box\":" + cursor.getInt(3);
				rtn += ",\"read\":" + ((cursor.getInt(4) == 1) ? "true" : "false");
				String subject = cursor.getString(5);
				subject = (subject == null) ? "" : Escape.escape(new String(subject.getBytes("8859-1"), "utf-8"));
				rtn += ",\"sub\":\"" + subject + "\"";
				rtn += "}";
			}
			cursor.close();
			return "[" + rtn + "]";
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
			return "[]";
		}
	}

	public String getAddresses(long id) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		try {
			cursor = contentResolver.query(Uri.parse(CONTENT_URI_MMS + id + "/addr"), ADDR_COLUMNS, null, null, null);
			if (cursor == null || cursor.getCount() == 0) return "[]";
			String rtn = "";
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				if (i > 0) rtn += ",";
				rtn += "{";
				rtn += "\"_id\":" + cursor.getString(0);
				rtn += ",\"msg_id\":" + cursor.getString(1);
				rtn += ",\"contact_id\":" + cursor.getString(2);
				rtn += ",\"address\":\"" + cursor.getString(3) + "\"";
				rtn += ",\"type\":" + cursor.getString(4);
				rtn += ",\"charset\":" + cursor.getString(5);
				rtn += "}";
			}
			cursor.close();
			return "[" + rtn + "]";
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
			return "[]";
		}
	}

	public String getParts(long id) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		try {
			cursor = contentResolver.query(Uri.parse(CONTENT_URI_MMS_PART), PART_COLUMNS, "mid=" + id, null, null);
			if (cursor == null || cursor.getCount() == 0) return "[]";
			String rtn = "";
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				if (i > 0) rtn += ",";
				rtn += "{";
				rtn += "\"_id\":" + cursor.getString(0);
				rtn += ",\"mid\":" + cursor.getString(1);
				rtn += ",\"seq\":" + cursor.getString(2);
				rtn += ",\"ct\":\"" + cursor.getString(3) + "\"";
				rtn += ",\"name\":\"" + ((cursor.getString(4) == null) ? "" : cursor.getString(4)) + "\"";
				rtn += ",\"chset\":\"" + ((cursor.getString(5) == null) ? "" : cursor.getString(5)) + "\"";
				rtn += ",\"cd\":\"" + ((cursor.getString(6) == null) ? "" : cursor.getString(6)) + "\"";
				rtn += ",\"fn\":\"" + ((cursor.getString(7) == null) ? "" : cursor.getString(7)) + "\"";
				rtn += ",\"cid\":\"" + cursor.getString(8) + "\"";
				rtn += ",\"cl\":\"" + ((cursor.getString(9) == null) ? "" : cursor.getString(9)) + "\"";
				rtn += ",\"ctt_s\":\"" + ((cursor.getString(10) == null) ? "" : cursor.getString(10)) + "\"";
				rtn += ",\"ctt_t\":\"" + ((cursor.getString(11) == null) ? "" : cursor.getString(11)) + "\"";
				rtn += ",\"_data\":\"" + ((cursor.getString(12) == null) ? "" : cursor.getString(12)) + "\"";
				rtn += ",\"text\":\"" + Escape.escape(cursor.getString(13)) + "\"";
				rtn += "}";
			}
			cursor.close();
			return "[" + rtn + "]";
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
			return "[]";
		}
	}

	public boolean extract(long id, String path) {
		if (Utilities.prepareWriteFile(path + "/tmp_" + System.currentTimeMillis()) == null) {
			mBrowser.exception(getInterfaceName(), "Invalid path:" + path);
			return false;
		}
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		InputStream in = null;
		ByteArrayOutputStream out = null;
		try {
			cursor = contentResolver.query(Uri.parse(CONTENT_URI_MMS_PART), PART_COLUMNS, "mid=" + id, null, null);
			if (cursor == null || cursor.getCount() == 0) return true;
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				String targetFile = cursor.getString(8);
				targetFile = path + "/" + targetFile.substring(1, targetFile.length() - 1);
				byte[] bytes = null;
				String mimetype = cursor.getString(3);
				if (mimetype.equalsIgnoreCase("application/smil")) {
					bytes = (cursor.getString(13) == null) ? null : cursor.getString(13).getBytes("UTF-8");
				} else if (Integer.parseInt(Build.VERSION.SDK) >= 5 && mimetype.equalsIgnoreCase("text/plain")) {
					bytes = (cursor.getString(13) == null) ? null : cursor.getString(13).getBytes("UTF-8");
				} else {
					Uri partURI = Uri.parse("content://mms/part/" + cursor.getString(0));
					out = new ByteArrayOutputStream();
					in = mContext.getContentResolver().openInputStream(partURI);
					byte[] buffer = new byte[1024];
					int len = in.read(buffer);
					while (len >= 0) {
						out.write(buffer, 0, len);
						len = in.read(buffer);
					}
					bytes = out.toByteArray();
				}
				Utilities.putContent(targetFile, bytes);
			}
			cursor.close();
			return true;
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
			if (in != null) try {
				in.close();
			} catch (IOException e1) {
			}
			return false;
		}
	}

}
